package com.tensai.core.mvc.system.service.imp;

import com.tensai.core.mvc.base.service.imp.BaseIdServiceImpl;
import com.tensai.core.mvc.base.tools.XTree;
import com.tensai.core.mvc.system.dao.ISysResourceDao;
import com.tensai.core.mvc.system.entry.SysResource;
import com.tensai.core.mvc.system.service.ISysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Tensai
 *         2018-03-22 16:17
 */
@Service
public class SysResourceService extends BaseIdServiceImpl<SysResource, ISysResourceDao> implements ISysResourceService {
	
	@Autowired
	private ISysResourceDao sysResourceDao;

	/**
	 * 获取实现类的Dao层方法
	 *
	 * @return dao
	 */
	@Override
	protected ISysResourceDao getDao() {
		return sysResourceDao;
	}
	
	@Override
	public List<SysResource> findByResourceString(String url) {
		return sysResourceDao.findByResourceString(url);
	}

	@Override
	public List<SysResource> findByType(String type) {
		return getDao().findByType(type);
	}

	/**
	 * 获取当前用户权限分配情况
	 * @param checkedList	用户权限选择情况
	 * @return				用户权限XTree
	 */
	@Override
	public List<XTree> getUserAuth(List<Integer> checkedList) {
		List<SysResource> resourceList1 = getDao().findByLevel(1);
		List<SysResource> resourceList2 = getDao().findByLevel(2);
		List<SysResource> resourceList3 = getDao().findByLevel(3);
		if (resourceList3 != null) {
			resourceList2 = mergeMenus(resourceList3, resourceList2);
		}
		if (resourceList2 != null) {
			resourceList1 = mergeMenus(resourceList2, resourceList1);
		}
		List<XTree> xTreeList = new ArrayList<>();
		resourceList1.forEach(item -> {
			XTree xTree = new XTree(item, checkedList);
			xTreeList.add(xTree);
		});
		return xTreeList;
	}

	/**
	 * 两级菜单合并
	 * @param source 	子级权限
	 * @param target 	父级权限
	 * @return			合并列表
	 */
	private List<SysResource> mergeMenus(List<SysResource> source, List<SysResource> target) {
		Set<SysResource> sysResourceSet2 = new HashSet<>(target);
		target.clear();
		source.forEach(item ->
				sysResourceSet2.add(item.getParent())
		);
		target = new ArrayList<>(sysResourceSet2);
		List<SysResource> finalTarget = target;
		source.forEach(sysResource2 ->
				finalTarget.forEach(sysResource1 -> {
					if (sysResource2.getParent().getId().equals(sysResource1.getId())) {
						if (sysResource1.getSysResourceList() == null) {
							sysResource1.setSysResourceList(new ArrayList<>());
						}
						sysResource1.getSysResourceList().add(sysResource2);
					}
				})
		);
		return finalTarget;
	}

}
